<template>
	<!-- 我的预约 -->
	<view>
		<!-- 弹出层 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog cancelText="取消" confirmText="确定" title=" " content="确认取消该预约?" @confirm="dialogConfirm"
				@close="dialogClose">
			</uni-popup-dialog>
		</uni-popup>
		<view class="header" style="background-color: white;">
			<!-- 搜索框 -->
			<div class="set_div">
				<input class="set_inupt" v-model="val" type="text" @click="tpseek" placeholder="搜索标题" disabled />
				<!-- 列表 -->
				<div class="filters">
					<view v-for="(filter, index) in filters" :key="filter.value">
						<span class="ss" :class="{ active: activeFilter === filter.value }"
							@click="handleClick(filter, index)">
							{{ filter.label }}
						</span>
					</view>
				</div>
			</div>
		</view>
		<view v-if="isnull" class="is--tag">暂无记录哦~</view>
		<view class="container" v-for="(list, index) in cardlist" :key="list.id">
			<view class="state">
				<text>可使用</text>
			</view>
			<view class="header">
				<text class="name">{{ list.sname }}</text>
			</view>
			<view class="info">
				<text>姓名:</text><text>{{ list.uname }}</text>
			</view>
			<view class="info">
				<text>时间:</text><text>{{ list.utime }}</text>
			</view>
			<view class="buttons">
				<button class="primary" type="primary" @click="viewDetails(list.id)">查看详情</button>
				<button class="default" type="default" @click="cancel(list.id)">取消</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow
	}
	from '@dcloudio/uni-app';
	import {
		getbyid,
		getDateById,
		getTimeById,
		showAppointmentByTypeAndUid,
		showAppointmentBySnameAndUid,
		deleteAppointment
	} from '@/request/api.js';

	const activeFilter = ref(null);
	const cardlist = ref([]);
	const alertDialog = ref(null);
	const deleteid = ref(null);
	const filters = ref([{
			label: '全部',
			value: 'sort'
		},
		{
			label: '可使用',
			value: 'star'
		},
		{
			label: '已核销',
			value: 'all'
		},
		{
			label: '已过期',
			value: 'gold'
		},
		{
			label: '系统取消',
			value: 'silver'
		},
	]);
	const token = ref(null); // 获取本地存储的token
	const val = ref('');
	const isnull = ref(false);

	const getToken = () => { // 获取本地存储的token
		const storedToken = uni.getStorageSync('token');
		token.value = storedToken || '';
	};

	onShow(async () => { //搜索跳转获取
		const result = uni.getStorageSync('result');
		val.value = result;
		// console.log("result:" + result)
		if (typeof result === 'string' && result.trim() !== '') { // 检查result是否为非空字符串
			activeFilter.value = "搜索";
			// console.log("搜索")
			const response = await showAppointmentBySnameAndUid({ // 调用showAppointmentBySnameAndUid函数并等待其完成
				uid: token.value,
				sname: result
			});
			// console.log(response)
			// console.log(response.data.code)
			if (response.data.code === 500) {
				cardlist.value = '';
				// console.log(cardlist.value)
			} else {
				await showAppointment(response); // 显示showAppointmentBySnameAndUid函数的响应结果
			}

		}
		uni.removeStorageSync('result');
	});
	onLoad(async (options) => { // 页面加载时获取用户数据。这里的 options 参数包含了页面加载时传递的参数
		console.log('页面加载时获取用户数据', options);
		activeFilter.value = options.event;
		getToken();
	});
	onMounted(async () => { //我的预约显示
		try {
			await showAppointment(await showApp());
		} catch (error) {
			console.error("请求失败:", error);
		}
	});

	function tpseek() { //跳转搜索页面
		uni.navigateTo({
			url: `/pages/user/seek/seek?tid=${2}`
		});
	}

	const handleClick = async (filter) => { //选择查询的预约状态
		val.value = '';
		activeFilter.value = filter.value;
		await showAppointment(await showApp());
	};

	const showApp = async () => { //获取我的预约数组
		console.log(token.value)
		const o = {
			uid: token.value,
			type: activeFilter.value
		};
		return await showAppointmentByTypeAndUid(o);
	}

	const showAppointment = async (response) => {
		// console.log(response);
		try {
			const promises = response.data.data.map(item => Promise.all([
				getbyid({
					id: item.sid
				}),
				getDateById({
					id: item.sdateid
				}),
				getTimeById({
					id: item.stimeid
				})
			]).then(results => {
				const [response, req, reql] = results;
				let date = new Date(req.data.data.date);
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2, '0');
				let weekDay = date.getDay();
				let weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
				let weekDayText = weekDays[weekDay];
				return {
					id: item.id,
					sname: response.data.data.name,
					uname: item.customername,
					utime: `${year}年${month}月${day}日(${weekDayText}) ${reql.data.data.time}`
				};
			}));
			// console.log(promises.length)
			if (promises.length === 0) {
				// console.log("暂无记录哦~")
				isnull.value = true;
				cardlist.value = '';
			} else {
				cardlist.value = await Promise.all(promises);
			}
		} catch (error) {
			console.error("Error fetching showAppointment:", error);
		}
	}

	function viewDetails(id) { //查看我的预约详情
		uni.navigateTo({
			url: `/pages/user/appointment/myappdt?id=${id}`
		});
	}

	const cancel = (id) => { //打开弹层并传输要删除的id
		alertDialog.value.open();
		deleteid.value = id;
		console.log(`删除：${id}`);
	};

	const dialogClose = () => { //点击取消关闭弹层不执行任何操作
		console.log(`点击取消`);
	};

	async function dialogConfirm() { //点击确认根据id取消我的预约
		console.log('点击确认:' + deleteid.value);
		try {
			const res = await deleteAppointment({
				id: deleteid.value
			});
			if (res.data.code === 200) {
				await showAppointment(await showApp());
			} else {
				console.log(res.data.msg);
			}
		} catch (error) {
			console.error("Error fetching deleteAppointment:", error);
		}
	}
</script>

<style>
	.is--tag {
		color: gray;
		text-align: center;
		width: 100%;
		margin-top: 20px;
		font-size: 16px;
	}

	.set_div {
		padding: 20rpx 40rpx;
		background-color: white;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
	}

	.set_inupt {
		height: 68rpx;
		width: 94%;
		padding-left: 20px;
		border-radius: 16rpx;
		background-color: #efefef;
		margin-bottom: 20px;
	}

	.state {
		color: #5ec36c;
		background-color: #d7f0db;
		padding: 5px;
		border-radius: 10px;
		width: 55px;
		margin-top: -10px;
		margin-left: -10px;
		font-size: 15px;
		text-align: center;
	}

	.default {
		border-radius: 10px;
		font-size: 16px;
		margin: 5px;
	}

	.primary {
		border-radius: 10px;
		margin: 5px;
		font-size: 16px;
	}

	.buttons {
		margin: 10px;
	}

	.info {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.info text:first-child {
		color: #cacaca;
		margin-right: 15px;
	}

	.info text {
		color: #cacaca;
	}

	.container {
		border-radius: 10px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		margin: 10px;
		padding: 10px;
		background-color: #ffffff;
	}

	.header {
		padding: 5px;
	}

	.ss {
		margin: 0px 2px;
		padding-bottom: 4px;
		font-size: 16px;
	}

	.ss.active {
		color: #5500ff;
		border-bottom: 3px #5500ff solid;
		font-weight: bold;
	}

	.ss:hover {
		color: #5500ff;
	}

	.filters {
		display: flex;
		gap: 10px;
		margin-bottom: 5px;
	}
</style>